﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web;
using DHQGHN.DAL.BO.TDT;
using DHQGHN.DAL.Models.DanhMuc;
using DHQGHN.DAL.Models.TDT;

namespace DHQGHN.Services.TDT
{
    public class AreaService : IAreaService
    {
        private AreaBO areaBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(AreaService));
        #region Constructors
        /// <summary>
        /// 
        /// </summary>
        public AreaService()
        {
            //string connString = ConfigurationManager.ConnectionStrings["DHQGHN_TDT.ConnectionString"].ConnectionString;
            areaBO = new AreaBO(DHQGHN.DAL.Common.ConnectionUtil.TKTHDS_TDT_CONNECTION_STRING);
        }
        #endregion

        #region Service Methods
        /// <summary>
        /// 
        /// </summary>
        /// <param name="eaCode"></param>
        /// <returns></returns>
        public IEnumerable<DAL.Models.TDT.Area> GetAll()
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Area>();
                }
                else
                {
                    return areaBO.GetAll();
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIdx"></param>
        /// <returns></returns>
        public IEnumerable<DAL.Models.TDT.Area> GetAllPaging(string pageSize, string pageIdx)
        {
            try
            {
                if (string.IsNullOrEmpty(pageSize)
                    || string.IsNullOrEmpty(pageIdx))
                {
                    Fault.ValidationFault fault = new Fault.ValidationFault()
                    {
                        Result = false,
                        Message = "Thiếu tham số",
                        Description = "Thiếu tham số"
                    };

                    throw new FaultException<Fault.ValidationFault>(fault);
                }

                int ipageSize, ipageIdx;
                if (int.TryParse(pageSize, out ipageSize) == false
                    || int.TryParse(pageIdx, out ipageIdx) == false)
                {
                    Fault.ValidationFault fault = new Fault.ValidationFault()
                    {
                        Result = false,
                        Message = "Tham số PageSize (hoặc PageIdx) sai định dạng!",
                        Description = "Tham số PageSize (hoặc PageIdx) sai định dạng!"
                    };

                    throw new FaultException<Fault.ValidationFault>(fault);
                }
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Area>();
                }
                else
                {
                    return areaBO.GetAllPaging(ipageSize, ipageIdx);
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="areaID"></param>
        /// <returns></returns>
        public DAL.Models.TDT.Area GetByID(string areaID)
        {
            try
            {
                string id = "-1";

                if (string.IsNullOrEmpty(areaID))
                {
                    Fault.ValidationFault fault = new Fault.ValidationFault()
                    {
                        Result = false,
                        Message = "Thiếu tham số",
                        Description = "Thiếu tham số"
                    };

                    throw new FaultException<Fault.ValidationFault>(fault);
                }
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new Area();
                }
                else
                {
                    id = areaID;
                    return areaBO.GetById(id);
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }

        public List<PM3_AREA> GetByUserNamePM3(string UserName)
        {
            try
            {              
                if (string.IsNullOrEmpty(UserName))
                {
                    Fault.ValidationFault fault = new Fault.ValidationFault()
                    {
                        Result = false,
                        Message = "Thiếu tham số",
                        Description = "Thiếu tham số"
                    };

                    throw new FaultException<Fault.ValidationFault>(fault);
                }
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<PM3_AREA>();
                }
                else
                {
                    return areaBO.GetByUserNamePM3(UserName);
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ea"></param>
        public void AddArea(DAL.Models.TDT.Area ea)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                }
                else
                {
                    areaBO.Save(ea);
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="eaID"></param>
        public void DeleteArea(string eaID)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                }
                else
                {
                    areaBO.Delete(eaID);
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ea"></param>
        public void EditArea(DAL.Models.TDT.Area ea)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                }
                else
                {
                    areaBO.Save(ea);
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        /// <summary>
        /// phunx1, 20150512: lay danh sach dia ban theo ma khu vuc hanh chinh
        /// </summary>
        /// <param name="adminCode"></param>
        /// <returns></returns>
        public IEnumerable<DAL.Models.TDT.Area> GetByAdminCode(string adminCode)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Area>();
                }
                else
                {
                    return areaBO.GetByAdminCode(adminCode);
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    //new FaultReason(string.Format("{0}", "Service fault exception")));
                    new FaultReason(string.Format("xx{0}", ex.Message)));
            }
        }

        /// <summary>
        /// 20150722: lay danh sach dia ban theo ma khu vuc hanh chinh //quyvd
        /// </summary>
        /// <param name="adminCode"></param>
        /// <returns></returns>
        public IEnumerable<DAL.Models.TDT.Area> GetByUserName(string UserName)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Area>();
                }
                else
                {
                    return areaBO.GetByUserName(UserName);
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    //new FaultReason(string.Format("{0}", "Service fault exception")));
                    new FaultReason(string.Format("xx{0}", ex.Message)));
            }
        }

        /// <summary>
        /// Datlq, get danh sach dia ban dieu tra theo ma khu vuc hanh chinh de mapping voi dieu tra vien
        /// </summary>
        /// <param name="adminCode"></param>
        /// <returns></returns>
        public IEnumerable<DAL.Models.TDT.Area> GetByAdminCode_MappingEnum(string adminCode, string enumID)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Area>();
                }
                else
                {
                    return areaBO.GetByAdminCode_MappingEnum(adminCode, enumID);
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    //new FaultReason(string.Format("{0}", "Service fault exception")));
                    new FaultReason(string.Format("xx{0}", ex.Message)));
            }
        }

        /// <summary>
        /// Datlq, get danh sach dia ban dieu tra theo ma khu vuc hanh chinh de mapping voi dieu tra vien
        /// </summary>
        /// <param name="adminCode"></param>
        /// <returns></returns>
        public IEnumerable<DAL.Models.TDT.Area> GetByAdminCode_NotMappingEnum(string adminCode, string enumID)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Area>();
                }
                else
                {
                    return areaBO.GetByAdminCode_NotMappingEnum(adminCode, enumID);
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    //new FaultReason(string.Format("{0}", "Service fault exception")));
                    new FaultReason(string.Format("xx{0}", ex.Message)));
            }
        }

        public List<DAL.Models.TDT.Area> GetForMapping(GetAreaConvert obj)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Area>();
                }
                else
                {
                    return areaBO.GetForMapping(obj);
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    //new FaultReason(string.Format("{0}", "Service fault exception")));
                    new FaultReason(string.Format("xx{0}", ex.Message)));
            }
        }
        /// <summary>
        /// phunx1, 20150514: luu danh sach toa do ranh gioi dia ban dieu tra
        /// </summary>
        /// <param name="arrPoints"></param>
        public void AddAreaBoundPoint(string arrPoints)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                }
                else
                {
                    string strAreaCode;
                    string[] listPoints = arrPoints.Split('-');
                    strAreaCode = listPoints[0];

                    areaBO.SaveBoundPoints(arrPoints.Remove(0, listPoints[0].Length + 1), strAreaCode);
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }
        /// <summary>
        /// phunx1: 20150529: method lay danh sach toa do ranh gioi theo dia ban dieu tra
        /// </summary>
        /// <param name="areaCode"></param>
        /// <returns></returns>
        public IEnumerable<DAL.Models.TDT.AreaBoundPointMD> GetAreaBoundPointByAreaCode(string areaCode)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<AreaBoundPointMD>();
                }
                else
                {
                    return areaBO.GetAreaBoundPoint(areaCode);
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    //new FaultReason(string.Format("{0}", "Service fault exception")));
                    new FaultReason(string.Format("{0}", ex.Message)));
            }
        }
        #endregion

        IEnumerable<AREA> IAreaService.GetNewListsTablet(string lastUpdated)
        {
            //HeaderInfo h = new HeaderInfo();
            MasterListTablet jret = new MasterListTablet();
            try
            {
                if (string.IsNullOrEmpty(lastUpdated))
                {
                    Fault.ValidationFault fault = new Fault.ValidationFault()
                    {
                        Result = false,
                        Message = "Thiếu tham số",
                        Description = "Thiếu tham số"
                    };


                    jret.ErrorCode = -1;
                    jret.ErrorMessage = "Thiếu tham số";
                    jret.CurrentTime = DHQGHN.Common.Utils.GetCurrentTimeNow();
                    jret.Data = null;

                    return null;
                }

                string formatString = "yyyyMMddHHmmss";
                //string sample = "20100611221912";
                DateTime _lastUpdated;
                try
                {
                    _lastUpdated = DateTime.ParseExact(lastUpdated, formatString, null);
                }
                catch (Exception ex)
                {
                    Fault.ValidationFault fault = new Fault.ValidationFault()
                    {
                        Result = false,
                        Message = "Tham số PageSize (hoặc PageIdx) sai định dạng!",
                        Description = "Tham số PageSize (hoặc PageIdx) sai định dạng!"
                    };

                    jret.ErrorCode = -2;
                    jret.ErrorMessage = "Tham số PageSize (hoặc PageIdx) sai định dạng!";
                    jret.CurrentTime = DHQGHN.Common.Utils.GetCurrentTimeNow();
                    jret.Data = null;
                    logger.Error(ex.ToString());
                    return null;
                }

                List<DHQGHN.DAL.Models.DanhMuc.AREA> ret = areaBO.GetNewLists(_lastUpdated);

                return ret; //jret;              
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }



        public List<Area> SearchArea(SearchAreaModel search)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<Area>();
                }
                else
                {
                    return areaBO.SearchArea(search);
                }

            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        public List<AREA> GetByADMUnitCode(string AdmUnitCode)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return new List<AREA>();
                }
                else
                {
                    List<AREA> ret = areaBO.GetByADMUnitCode(AdmUnitCode);
                    return ret;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    new FaultReason(string.Format("{0}", "Service fault exception")));
            }
        }

        /// <summary>
        /// Quyvd, get danh sach dia ban dieu tra theo ma khu vuc hanh chinh de mapping voi dieu tra vien
        /// </summary>
        /// <param name="adminCode"></param>
        /// <returns></returns>
        public bool CheckForAreaName(string AREA_NAME, string adm_unit_id, string AREA_ID)
        {
            try
            {
                if (!RoleChecking.CanAccess(WebOperationContext.Current.IncomingRequest.Headers))
                {
                    RoleChecking.ThrowUnauthorizedException();
                    return false;
                }
                else
                {
                    bool ret = areaBO.CheckForAreaName(AREA_NAME, adm_unit_id, AREA_ID);
                    return ret;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw new FaultException<Fault.UnexpectedServiceFault>(
                    new Fault.UnexpectedServiceFault
                    {
                        ErrorMessage = ex.Message,
                        Source = ex.Source,
                        Target = ex.TargetSite.ToString(),
                        StackTrace = ex.StackTrace
                    },
                    //new FaultReason(string.Format("{0}", "Service fault exception")));
                    new FaultReason(string.Format("xx{0}", ex.Message)));
            }
        }

    }
}